package com.yingpai.fitness.dvp_2_0.main.fragment.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.view.statusbar.StatusView;
import com.yingpai.fitness.dvp_2_0.main.activity.vip.VipCardActivity;
import com.yingpai.fitness.dvp_2_0.main.fragment.fitness.FitnessBikeFragment;
import com.yingpai.fitness.dvp_2_0.main.fragment.fitness.FitnessDieteticFragment;
import com.yingpai.fitness.dvp_2_0.main.fragment.fitness.FitnessFineChoosedFragment;
import com.yingpai.fitness.dvp_2_0.main.fragment.fitness.FitnessRunFragment;
import com.yingpai.fitness.dvp_2_0.main.widget.AddressTopPickTask;
import com.yingpai.fitness.entity.TabEntity;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import io.reactivex.functions.Consumer;

/**
 * 健身模块fragment
 * Created by ASUS on 2018/11/2.
 */

public class FitnessFragment extends CommonFragment {

    @BindView(R.id.status_view)
    StatusView statusView;
    @BindView(R.id.centerTitleTv)
    TextView centerTitleTv;
    @BindView(R.id.tablayout)
    CommonTabLayout tablayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    Unbinder unbinder;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    /**
     * 地步导航栏标题数组
     */
    private String[] mTitlesTopTab = {"精选", "跑步", "骑行", "饮食"};
    /**
     * 包含 精选   跑步    骑车   饮食    的Fragment集合
     */
    private ArrayList<Fragment> mFragmentParentList = new ArrayList<>();
    private PagerAdapter pagerAdapter;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    public static FitnessFragment newInstance() {
        return new FitnessFragment();
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_fragment_fitness, container, false);
        unbinder = ButterKnife.bind(this, view);
        if (!rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
            rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean) {
                        initLocation();
                        mLocationClient.start();//重新定位
                    } else {
                        showToast("拒绝权限可能导致部分功能不能使用");
                    }
                }
            });
        } else {
            initLocation();
            mLocationClient.start();//重新定位
        }

        viewpager.setOffscreenPageLimit(mTitlesTopTab.length);//设置预加载页面数量,全部加载!
        initChildFragment();
        viewpager.setAdapter(pagerAdapter);
        for (int i = 0; i < mTitlesTopTab.length; i++) {
            mTabEntities.add(new TabEntity(mTitlesTopTab[i], 0, 0));
        }
        tablayout.setTabData(mTabEntities);
        tablayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tablayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }

        });

        viewpager.setCurrentItem(0);
        return view;
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

//           int type =  location.getLocType();
//            String addr = location.getAddrStr();    //获取详细地址信息
//            String country = location.getCountry();    //获取国家
//            String province = location.getProvince();    //获取省份
//            String city = location.getCity();//获取城市
//            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            if (street != null) {
                centerTitleTv.setText(street);
            }

            mLocationClient.stop();
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        statusView.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.normal_status));

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    @OnClick({R.id.centerTitleTv, R.id.home_parent_tob_right_iv})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.centerTitleTv:
                initPick();
                break;
            case R.id.home_parent_tob_right_iv:
                startActivity(VipCardActivity.class);
                break;
        }
    }

    private void initPick() {
        AddressTopPickTask task = new AddressTopPickTask(context);
        task.setHideProvince(false);
        task.setHideCounty(false);
        task.setCallback(new AddressTopPickTask.Callback() {
            @Override
            public void onAddressInitFailed() {
                showToast("数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                if (county == null) {
                    centerTitleTv.setText(province.getAreaName() + city.getAreaName());
                } else {
                    centerTitleTv.setText(province.getAreaName() + city.getAreaName() + county.getAreaName());
                }
            }
        });
        task.execute("山西", "太原", "小店");
    }

    /**
     * 初始化子fragment
     */
    private void initChildFragment() {
        mFragmentParentList.add(FitnessFineChoosedFragment.getInstance());
        mFragmentParentList.add(FitnessRunFragment.getInstance());
        mFragmentParentList.add(FitnessBikeFragment.getInstance());
        mFragmentParentList.add(FitnessDieteticFragment.getInstance());

        pagerAdapter = new PagerAdapter(this.getChildFragmentManager());
    }

    private void initLocation() {
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                Toast.makeText(this, "打开后直接点击返回键即可，若不打开返回下次将再次出现", Toast.LENGTH_SHORT).show();
            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
        }

        mLocationClient = new LocationClient(context);
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setIsNeedAddress(true);
        //是否需要地址信息 默认不需要

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认gcj02
        //gcj02：国测局坐标；
        //bd09ll：百度经纬度坐标；
        //bd09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回wgs84类型坐标

        option.setScanSpan(0);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前WiFi是否超出有效期，若超出有效期，会先重新扫描WiFi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    private class PagerAdapter extends FragmentPagerAdapter {

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentParentList != null ? mFragmentParentList.get(position) : null;
        }

        @Override
        public int getCount() {
            return mFragmentParentList != null ? mFragmentParentList.size() : 0;
        }

        /**
         * 文本
         *
         * @param position
         * @return
         */
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitlesTopTab != null ? mTitlesTopTab[position] : "";
        }
    }

}
